<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="保养单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入保养单号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="模具编码" prop="accountId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.accountId" placeholder="请选择模具"
          check-strictly filterable>
          <el-option v-for="dict in accountList" :key="dict.id" :label="dict.code" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="图号" prop="drawingNoId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.drawingNoId"
          placeholder="请选择图号" check-strictly filterable>
          <el-option v-for="dict in drawingNoList" :key="dict.id" :label="dict.drawingNo" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="保养人" prop="assigneerId">
        <el-select v-model="queryParams.assigneerId" filterable clearable placeholder="请选择保养人" class="!w-240px">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="保养类型" prop="upkeepId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.upkeepId" placeholder="请选择保养类型"
          check-strictly filterable>
          <el-option v-for="dict in upkeepCategoryList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_UPKEEP_TOBE_STATUS)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="下达时间" prop="taskCreateTime">
        <el-date-picker v-model="queryParams.taskCreateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>

        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mold:upkeep-task:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>

      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange" border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="保养单号" align="center" prop="code">
        <template #default="scope">
          <el-button type="primary" link @click="openDetail(scope.row.id)">
            {{ scope.row.code }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="图号" align="center" prop="drawingNo" min-width="90" />
      <el-table-column label="模具" align="center" prop="accountName" min-width="90" />
      <el-table-column label="编码" align="center" prop="accountCode" min-width="120" />
      <el-table-column label="保养类型" align="center" prop="upkeepCategory" min-width="90" />
      <el-table-column label="接收人" align="center" prop="assigneerName" />
      <el-table-column label="保养人" align="center">
        <template #default="scope">
          <span v-for="(userId, index) in scope.row.assigneerIds" :key="userId">
            {{userList.find(user => user.id === userId)?.nickname}}<span
              v-if="index < scope.row.assigneerIds.length - 1">, </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_UPKEEP_TOBE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="计划保养日期" align="center" prop="nextUpkeepTime" :formatter="dateFormatter" width="180px" />
      <!--       <el-table-column label="实际保养日期" align="center" prop="realUpkeepTime" :formatter="dateFormatter" width="180px" /> -->
      <el-table-column label="下达时间" align="center" prop="taskCreateTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="接收时间" align="center" prop="taskReceiveTime" :formatter="dateFormatter" width="180px" />
      <!-- <el-table-column label="作业开始时间" align="center" prop="jobStartTime" :formatter="dateFormatter" width="180px" /> -->
      <el-table-column label="任务开始时间" align="center" prop="taskStartTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="任务结束时间" align="center" prop="taskEndTime" :formatter="dateFormatter" width="180px" />

      <el-table-column label="操作" align="center" min-width="150px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleReceive(scope.row.id)" v-if="scope.row.status === 2">
            接收
          </el-button>
          <!--    <el-button link type="primary" @click="handleStartJob(scope.row.id)" v-if="scope.row.status === 3">
            开始作业
          </el-button> -->
          <el-button link type="primary" @click="handleWorkPort(scope.row.id)" v-if="scope.row.status === 3">
            报工
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mold:upkeep-task:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UpkeepTaskForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：报工界面 -->
  <UpkeepWorkPort ref="workPortRef" @success="getList" />

  <!-- 表单弹窗：详情界面 -->
  <UpkeepTaskDetail ref="detailRef" />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { UpkeepTaskApi, UpkeepTask, UpkeepTaskModStautus } from '@/api/mold/upkeeptask'
import UpkeepTaskForm from './UpkeepTaskForm.vue'
import UpkeepWorkPort from './UpkeepWorkPort.vue'
import UpkeepTaskDetail from './UpkeepTaskDetail.vue'
import { DrawingNoApi } from '@/api/mold/drawingno'
import { AccountApi } from '@/api/mold/account'
import { UpkeepCategoryApi } from '@/api/mold/upkeepcategory'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'

/** 模具保养任务 列表 */
defineOptions({ name: 'UpkeepTask' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<UpkeepTask[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  drawingNoId: undefined,
  accountId: undefined,
  assigneerId: undefined,
  upkeepId: undefined,
  status: undefined,
  nextUpkeepTime: [],
  realUpkeepTime: [],
  taskCreateTime: [],
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const drawingNoList = ref([])
const accountList = ref([])
const userList = ref<UserVO[]>([]) // 
const upkeepCategoryList = ref([])
const detailRef = ref() // 详情弹窗引用

const getUpkeepCategoryList = async () => {
  upkeepCategoryList.value = []
  const data = await UpkeepCategoryApi.getUpkeepCategoryAll()
  upkeepCategoryList.value = data
}

/** 获取保养人列表 */
const getUserList = async () => {
  try {
    userList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    message.error('获取保养人列表失败')
    console.error(error)
  }
}

const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
}

/** 获得图号列表 */
const getDrawingNoList = async () => {
  drawingNoList.value = []
  const data = await DrawingNoApi.getDrawingNoAll()
  drawingNoList.value = data
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UpkeepTaskApi.getUpkeepTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()

const workPortRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

//接收
const handleReceive = (id: number) => {
  const status_a: UpkeepTaskModStautus = {
    id: id,
    status: 3,
    data: "" // 3为"已接收"状态，具体值请根据实际业务调整
  }
  modStatus(status_a)
}

//保养
const handleStartJob = (id: number) => {
  //弹窗提醒：开始作业后，将会记录当前时间为作业开始时间，是否确定？
  message.confirm('确认开始作业吗？').then(() => {
    const status_a: UpkeepTaskModStautus = {
      id: id,
      status: 4,
      data: "" // 4为"已开始作业"状态，具体值请根据实际业务调整
    }
    modStatus(status_a)
  })
}

// 打开报工界面
const handleWorkPort = (id: number) => {
  workPortRef.value.open(id)
}

// 打开详情界面
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 调用状态接口 */
const modStatus = async (status_a: UpkeepTaskModStautus) => {
  try {
    await UpkeepTaskApi.modStatus(status_a)
    message.success('操作成功')
    await getList()
  } catch (error) {
    message.error('操作失败')
    // 可选：console.error(error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UpkeepTaskApi.deleteUpkeepTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除模具保养任务 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await UpkeepTaskApi.deleteUpkeepTaskList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: UpkeepTask[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UpkeepTaskApi.exportUpkeepTask(queryParams)
    download.excel(data, '模具保养任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getUserList()
  getUpkeepCategoryList()
  getAccountList()
  getDrawingNoList()
  getList()
})
</script>